<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="发起申请" width="40%" @ok="handleSubmit">
    <!--<a-empty description="无流程可供选择" v-if="activeKeyAll.length==0" />-->
    <div>
      <a-input-search style="margin-bottom: 10px;width: 200px"
                      placeholder="输入流程名称" @search="onSearchProcess" />
      <a-collapse v-model:activeKey="activeKey2.data">
        <a-collapse-panel :key="value" v-for="(value, index)  in activeKeyAll.data" :header="filterDictText(dictOptions.data,value)||'未分类'" >
          <a-list :grid="{ gutter: 10, column: 1 }" :data-source="processDataMap.data[value]">
            <!-- <template   v-for="(item, index) in processDataMap.data[value]"> -->
              <template #renderItem="{ item }">
                <a-list-item>
              <a-card :title="item.name">
                <template #extra>
                  <a href="javascript:void (0)" @click="chooseProcess(item)">发起申请</a>
                </template>
                <p>版本：v.{{item.version}}</p>
                <br/>
                <p>说明：{{item.description}}</p>
              </a-card>
            </a-list-item>
            </template>
          </a-list>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </BasicDrawer>
  <itemModal @register="registerModal" @success="handleSuccess"></itemModal>
</template>

<script lang="ts" setup>
  import {ref, computed ,unref,reactive} from 'vue';
  import { BasicDrawer, useDrawerInner } from '/src/components/Drawer';
  import {BasicForm, useForm} from '/@/components/Form/index';
  import {formSchema} from '../myApply.data';
  import {getProcessDataList } from '../myApply.api';

  import { initDictOptions,filterDictText } from '/@/utils/dict';
  import { useMessage } from '/src/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import itemModal from './itemModal.vue';
  // import DesignFromShowModal from '/@/views/fromCreate/components/DesignFromShowModal.vue';

  import {useModal} from '/@/components/Modal';


  const [registerModal, {openModal:addOpenModal}] = useModal();

  // Emits声明
  const emit = defineEmits(['register','success']);
  const isUpdate = ref(true);
   const  activeKey2 = reactive({data:[]});
  const  dictOptions = reactive({data:[]});
  const  activeKeyAll = reactive({data:[]});
  const  processDataMap= reactive({data:{}});
  const searchProcessKey= ref('');

  //表单配置
  const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
    //labelWidth: 150,
    // schemas: processDataMap,
    showActionButtonGroup: false,
    baseColProps: {span: 24}
  });
  //表单赋值
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    try{
      setDrawerProps({confirmLoading: true});
      initDictConfig();
      getProcessList();
  }finally {
      //重置表单
      // await resetFields();
      setDrawerProps({
        confirmLoading: false,
        // showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter
      });
    }
    // isUpdate.value = !!data?.isUpdate;
    // if (unref(isUpdate)) {

      // const resdata = await defHttp.get({url: '/bus/busServiceinfo/queryById', params});

      //表单赋值
      // await setFieldsValue({
      //   ...resdata,
      // });
    // }
    //判断不同参数显示不同表格
    // if(data.aa){
    //   // 隐藏底部时禁用整个表单
    //   setProps({ disabled: !data?.showFooter})
    // }else{
    //   setProps({ disabled: !data?.showFooter,schemas:null })
    // }

  });
  function getProcessList() {
    getProcessDataList({status:1,roles:true}).then(res=>{
      let result = res||[];
      if (result.length>0){
        activeKeyAll.data=[];
        activeKey2.data=[];
        processDataMap.data={};
        let skey = searchProcessKey.value;
        if (skey==""){ //过滤条件
          // result = _.filter(result, function(o) { return o.name.indexOf(searchProcessKey)>-1; });
          result = result.filter((o)=> { return o.name.indexOf(skey)>-1; });
        };
        //根据categoryId类型分组
        const aa=[...new Set(result.map(ps=>ps.categoryId))];
        activeKeyAll.data=aa;
        activeKey2.data=activeKeyAll.data;
        let dataContainer = {}; //存分组的
        result.map(item=>{
          dataContainer[item.categoryId]=dataContainer[item.categoryId] || [];
          dataContainer[item.categoryId].push(item);
        })
        processDataMap.data=dataContainer;
      }
    })
  }

  function initDictConfig() {
    //初始化字典 - 流程分类
    initDictOptions('bpm_process_type').then((res) => {
        dictOptions.data = res;
    });
  };
  function filterDictText(dictOptions, text) {
    if (dictOptions instanceof Array) {
      for (let dictItem of dictOptions) {
        if (text === dictItem.value) {
          return dictItem.text
        }
      }
    }
    return text||text=='null'?'':text
  };
  //查询
  function onSearchProcess(value) {
    searchProcessKey.value = value;
    getProcessList()
  };
  //提交
  function chooseProcess(record) {  
    // record.designFormId=record.routeName;
    // record.isShow=true;
    addOpenModal(true, {
       record,
       isUpdate: true,
       showFooter: false,
     });
    // if (!v.routeName) {
    //   createMessage.warning(
    //     "该流程信息未配置表单，请联系开发人员！"
    //   );
    //   return;
    // }
    // this.lcModa.formComponent = this.getFormComponent(v.routeName).component;
    // this.lcModa.title = '发起流程：'+v.name;
    // this.lcModa.isNew = true;
    // this.lcModa.processData = v;
    // this.lcModa.visible = true;
    // console.log("发起",v)

    
  };
  function handleSuccess(){
        //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success');
    }
  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      setDrawerProps({confirmLoading: true});
      //修改为审核数据
      let data = {
        ids: [values.id],
        fwIspass: values.fwIspass==='0'? null : values.fwIspass,
        fwDescription: values.fwDescription
      }
      //提交表单
      // await saveOrUpdate(data, isUpdate.value);
      // await checkBatch(data);
      //关闭弹窗
      closeDrawer();
      //刷新列表
      emit('success');
    } finally {
      setDrawerProps({confirmLoading: false});
    }
  }
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number){
    width: 100%
  }

  :deep(.ant-calendar-picker){
    width: 100%
  }
</style>
